package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BookDetailsActivity;
import com.jjwxc.jwjskandriod.activity.FindActivity;
import com.jjwxc.jwjskandriod.adapter.AllSuggestViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.ListUserBookResponse;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class AdoleAuggestFragment extends Fragment {
    private View view;
    private RecyclerView rv_recently;
    private  AdoleAuggestAdapter adapter;

    public static long lastRefreshTime;
    private XRefreshView refreshView;
    private ImageView img_find;
    private int page = 0;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_adoleauggest, container, false);
            setViewId();
            setListener();
        }
        afterCreate(0);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListener() {
        rv_recently.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new AdoleAuggestAdapter(getActivity());
        rv_recently.setAdapter(adapter);
        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(getActivity()));
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);
        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                afterCreate(0);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                afterCreate(page * 10);
            }
        });

    }

    public void setViewId() {
        refreshView = view.findViewById(R.id.adole_view);
        rv_recently = view.findViewById(R.id.rv_adolestack);
        img_find = view.findViewById(R.id.img_find);
        rv_recently.setNestedScrollingEnabled(false);
        rv_recently.setFocusable(false);
        rv_recently.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_recently.addItemDecoration(new LinearLayouDecoration(getActivity(),
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        img_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FindActivity.class);
                startActivity(intent);
            }
        });
    }

    public void afterCreate(final int page) {
        ((FFActivity) getActivity()).post(Url.listUserInterestBook, null,
                ListUserBookResponse.class, new FFNetWorkCallBack<ListUserBookResponse>() {
            @Override
            public void onSuccess(ListUserBookResponse response) {
                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() <= 0) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.stopRefresh();
                        refreshView.setLoadComplete(false);
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }


                }

            }

            @Override
            public boolean onFail(ListUserBookResponse response) {
                return false;
            }
        },"{\"offset\":"+page+",\"isChildMode\":true,\"limit\":10}");

    }



    public class AdoleAuggestAdapter extends BaseRecyclerAdapter<AllSuggestViewHolder> {

        private Context context;


        private List<ListUserBookResponse.DataBean> mData = new ArrayList<>();


        public AdoleAuggestAdapter(Context cnt) {
            this.context = cnt;

        }

        @SuppressLint("NotifyDataSetChanged")
        public void addData(List<ListUserBookResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<ListUserBookResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public AllSuggestViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.allsuggest_item_list, parent, false);
            AllSuggestViewHolder viewHolder_text = new AllSuggestViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public AllSuggestViewHolder getViewHolder(View view) {
            return new AllSuggestViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(final AllSuggestViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            holder.tv_bookname_allsuggest.setText(mData.get(position).getName());
            holder.tv_book_allsuggest.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_allsuggest_tab.setText(mData.get(position).getChannlname());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            FFImageLoader.loadImage(getContext(), holder.img_allsuggest_item, mData.get(position).getCoverImgUrl(), mData.get(position).getBookId(), true);

            holder.cl_allsuggest.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                    MobclickAgent.onEvent(getContext(), UMConstant.SUGGEST_TUIJIAN_GUESS_CELL_CLICK);
                }
            });

        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }

    }

